package yunjiao.javatutorials.guava.base.functional;

import com.google.common.base.Equivalence;

/**
 * 组合多个等价关系
 *
 * @author yangyunjiao
 */
public class CombinedEquivalence {
    record Order(String orderId, String customerId, double amount) {

        // 创建组合键
        public String getCompositeKey() {
            return customerId + ":" + String.format("%.2f", amount);
        }
    }

    public static void main(String[] args) {
        // 基于客户ID的等价关系
        Equivalence<Order> customerEquivalence =
                Equivalence.equals().onResultOf(Order::customerId);

        // 基于金额范围的等价关系（将金额四舍五入到百位）
        Equivalence<Order> amountRangeEquivalence =
                Equivalence.equals().onResultOf(order -> Math.round(order.amount() / 100) * 100);

        // 基于组合键的等价关系
        Equivalence<Order> compositeEquivalence =
                Equivalence.equals().onResultOf(Order::getCompositeKey);

        Order order1 = new Order("O001", "CUST123", 245.50);
        Order order2 = new Order("O002", "CUST123", 255.75);
        Order order3 = new Order("O003", "CUST456", 245.50);

        System.out.println("基于客户ID比较:");
        System.out.println("order1 ≈ order2: " + customerEquivalence.equivalent(order1, order2));
        System.out.println("order1 ≈ order3: " + customerEquivalence.equivalent(order1, order3));

        System.out.println("\n基于金额范围比较:");
        System.out.println("order1 ≈ order2: " + amountRangeEquivalence.equivalent(order1, order2));
        System.out.println("order1 ≈ order3: " + amountRangeEquivalence.equivalent(order1, order3));

        System.out.println("\n基于组合键比较:");
        System.out.println("order1 ≈ order2: " + compositeEquivalence.equivalent(order1, order2));
        System.out.println("order1 ≈ order3: " + compositeEquivalence.equivalent(order1, order3));
    }
}
